using System;
using System.Collections.Generic;
using System.Text;

using KNCApp.Business;
using KNCApp.Business.Models;
using KNCApp.Business.Interfaces;

namespace KNCApp.Port
{
    class PressureReader : IReceiver
    {
        public static Pressure Pressure; 
        
        private PortHandler portHandler;
        private IDataParser parser;
        private List<IDataHandler> handlers;

        public PressureReader()
        {
            init(); 
        }

        private void init()
        {
            portHandler = new PortHandler(SettingsMgr.GetPressurePort());
            portHandler.BaudRate = 2400;
            handlers = new List<IDataHandler>();
        }

        public void RegisterParser(IDataParser dp)
        {
            parser = dp;
        }

        public void RegisterHandler(IDataHandler dh)
        {
            handlers.Add(dh);
        }


        public void Receive(string data)
        {
            if (parser != null)
            {
                Pressure pObj = parser.Parse(data) as Pressure;
                if (pObj != null)
                {
                    Pressure = pObj;
                    foreach (IDataHandler h in handlers)
                    {
                        h.HandleData(pObj);
                    }
                }
            }
        }

        public void Start()
        {
            if (portHandler != null)
            {
                if (parser != null)
                {
                    portHandler.StartReading(parser.GetMode(), this);
                }
                else
                {
                    portHandler.StartReading("", this);
                }
            }
        }

        public void Stop()
        {
            if(portHandler != null)
                portHandler.Stop("");
        }
    }
}
